package com.enzoism.springboot.dive.bis.iterator;

import lombok.Data;

/**
 * 【自定义】数组学习遍历
 */
@Data
public class MyIterationArray {
    private Object[] items;
    private int next = 0;

    // 初始化时，创建数组的尺寸为传入的size
    public MyIterationArray(int size) {
        items = new Object[size];
    }

    // 添加元素到数组的尾部
    public void add(Object x) {
        if (next < items.length) {
            items[next++] = x;
        }
    }

    // 内部类暴露
    public MyIterator selector() {
        return new MySelectorImpl();
    }

    // 测试方法
    public static void main(String[] args) {
        // 添加数据到数组
        int size = 10;
        MyIterationArray myIterationArray = new MyIterationArray(size);
        for (int i = 0; i < size; i++) {
            myIterationArray.add("小明" + i);
        }
        System.out.println(myIterationArray.toString());

        // 进行数据对象迭代
        MyIterator selector = myIterationArray.selector();
        while (!selector.isEnd()) {
            System.out.println(selector.current());
            selector.next();
        }
    }

    // 内部类直接共享外部类的变量
    public class MySelectorImpl implements MyIterator {
        private int i = 0;

        @Override
        public boolean isEnd() {
            return i == items.length;
        }

        @Override
        public Object current() {
            return items[i];
        }

        @Override
        public void next() {
            if (i < items.length) {
                i++;
            }
        }
    }
}